package com.example.excel.ui.activity.query;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.example.excel.base.BaseViewModel;
import com.example.excel.bean.BaseBean;
import com.example.excel.bean.InventoryBean;
import com.example.excel.bean.ListBean;
import com.example.excel.config.Constants;
import com.example.excel.db.InventoryController;
import com.example.excel.http.ApiException;
import com.example.excel.http.HttpManager;
import com.example.excel.utils.Utils;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;

public class InventoryViewModel extends BaseViewModel {

    public MutableLiveData<InventoryBean> mBean = new MutableLiveData<>();

    public InventoryViewModel(@NonNull Application application) {
        super(application);
    }

    public void query(final String code) {
        Observable.just(1).map(new Function<Integer, List<InventoryBean>>() {
            @io.reactivex.annotations.NonNull
            @Override
            public List<InventoryBean> apply(@io.reactivex.annotations.NonNull Integer integer) throws Exception {
                List<InventoryBean> b = InventoryController.getInstance().queryByCode(code);
                return b;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<InventoryBean>>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull List<InventoryBean> b) {
                if (b.size() > 0) {
                    mBean.setValue(b.get(0));
                } else {
                    mBean.setValue(null);
                }
                getDialog().setValue(false);
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                mBean.setValue(null);
                Utils.getInstance().showToast("e : " + e.getMessage());
                getDialog().setValue(false);
            }

            @Override
            public void onComplete() {
                getDialog().setValue(false);
            }
        });
    }
}
